﻿using log4net;
using ServerControl.Dal;
using ServerControl.Model;
using ServerControl.WebManage.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServerControl.Utils;

namespace ServerControl.WebManage.Controllers.Admin
{
	[RoutePrefix("admin/command")]
	[Auth(AllowRole = Model.Enum.Role.AdminOrUser)]
	public class CommandController : BaseController
	{
		private ILog logger = LogManager.GetLogger("CommandController");

		[Route("index")]
		public ActionResult Index()
		{
			return View();
		}

		/// <summary>
		/// 获取下载列表
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		[Route("list")]
		public JsonResult GetCommands(int pageIndex = 1, int pageSize = 20)
		{
			try
			{
				int records = 0;
				var commands = UserDal.GetCommands(ref records, pageIndex, pageSize);


				return new JsonNetResult { Data = new SuccessResult<List<Command>> { Data = commands, Count = records, Msg = "" } };
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
		}

		[HttpPost]
		[Route("edit")]
		public JsonResult AddOrEdit(Command command)
		{
			try
			{
				command.AddTime = DateTime.Now;
				var isSuccess = false;

				if (command.Id == 0)
				{
					isSuccess = UserDal.AddCommand(command);
				}
				else
				{
					isSuccess = UserDal.EditCommand(command);
				}

				if (isSuccess)
				{
					return new JsonNetResult { Data = new SuccessResult { Msg = "操作成功" } };
				}
				else
				{
					return new JsonNetResult { Data = new FailResult { Msg = "操作失败" } };
				}
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
		}

		[HttpPost]
		[Route("delete")]
		public JsonResult Delete(int id)
		{
			try
			{
				var isSuccess = UserDal.DeleteCommand(id);

				if (isSuccess)
				{
					return new JsonNetResult { Data = new SuccessResult { Msg = "操作成功" } };
				}
				else
				{
					return new JsonNetResult { Data = new FailResult { Msg = "操作失败" } };
				}
			}
			catch (Exception ex)
			{
				logger.Error(ex);
			}

			return new JsonNetResult { Data = new FailResult { Msg = "请求异常" } };
		}
	}
}